package camid.services.cloudmanager;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimerTask;

import camid.services.nameservice.INameService;

public class LoadAnalyserAgent extends TimerTask {

	private IClusterManagerRegistry registry;

	private INameService nameService;

	private ClusterManager clusterManager;

	public LoadAnalyserAgent(IClusterManagerRegistry registry,
			INameService nameService, ClusterManager clusterManager) {
		this.registry = registry;
		this.nameService = nameService;
		this.clusterManager = clusterManager;
	}

	@Override
	public void run() {

		List<String> nodeIds = this.nameService.getAllNodes();
		Map<String, Double> costMap = registry.getCostMap(nodeIds);

		double average = average(costMap);
		for(Entry<String,Double> entry : costMap.entrySet()) {
			String nodeId = entry.getKey();
			double cost = entry.getValue();
			if(cost > 0.7 && (cost - average) > 0.2) 
			{
				sendAlert(nodeId, 5);
			}
			else
			{
				sendAlert(nodeId, 0);
			}
		}

	}

	private double average(Map<String, Double> costMap) {
		double sum = 0.0;
		for (Entry<String, Double> entry : costMap.entrySet()) {
			sum += entry.getValue();
		}
		double average = sum / (double) costMap.size();
		return average;
	}

	private void sendAlert(String nodeId, int numberOfObjects) {
		this.clusterManager.sendAlert(nodeId, numberOfObjects);
	}
	

}
